package com.xjl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjl.constants.SystemConstants;
import com.xjl.domain.ResponseResult;
import com.xjl.domain.entity.Article;
import com.xjl.domain.entity.Category;
import com.xjl.domain.vo.ArticleDetailVo;
import com.xjl.domain.vo.ArticleListVo;
import com.xjl.domain.vo.HotArticleVo;
import com.xjl.domain.vo.PageVo;
import com.xjl.mapper.ArticleMapper;
import com.xjl.service.ArticleService;
import com.xjl.service.CategoryService;
import com.xjl.utils.BeanCopyUtils;
import com.xjl.utils.RedisCache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : xjl
 * @date : 2023-08-01
 **/
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章，封装成ResponseResult返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //如果直接写status，编译器不会检查拼写错误
        //按照浏览量降序排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多查询10条
        Page<Article> page = new Page<>(1,10);//第一页，每页10个
        page(page,queryWrapper);
        List<Article> articleList = page.getRecords();
        /**
         * 原本的Article含有的字段并不需要全部返回给前端，因此需要重新创建一个类，只包含需要返回的字段信息（HotArticleVo）
         */

        //使用bean拷贝
//        List<HotArticleVo> articleVos = new ArrayList<>();
//        for (Article article:articleList) {
//            HotArticleVo vo = new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            articleVos.add(vo);
//        }

        List<HotArticleVo> articleVos = BeanCopyUtils.copyBeanList(articleList, HotArticleVo.class);


        return ResponseResult.okResult(articleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        //如果有categoryId，就需要根据categoryId查
        queryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0,Article::getCategoryId,categoryId);

        //状态是正式发布
        queryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);

        //置顶文章在前面（is_top按降序排列）
        queryWrapper.orderByDesc(Article::getIsTop);

        //分页查询
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);

        //查询分类名称categoryName
        List<Article> articles = page.getRecords();
        //根据categoryId查询categoryName

        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());

//        for (Article article:articles) {
//            Category category=categoryService.getById(article.getCategoryId());
//            article.setCategoryName(category.getName());
//        }


        //封装查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);


        PageVo pageVo =new PageVo(articleListVos,page.getTotal());//把查到的集合和总个数封装到PageVo中
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);

        //从redis中读取article:viewCount
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());

        //转换成vo格式
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);

        //根据分类id查询分类名
        Long categoryId=articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (category!=null){
            //查到数据，可以设置vo中分类名
            articleDetailVo.setCategoryName(category.getName());
        }

        //封装响应体
        return ResponseResult.okResult(articleDetailVo);
    }


    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中的浏览量
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();
    }
}
